JavaScript snippet
JavaScript
snippet
跨頁面通訊
於網址儲存狀態
expandedForm
code:javascript
const expandedForm = (n) =>
n
.toString()
.split("")
.reverse()
.map((a, i) => a * Math.pow(10, i))
.filter((a) => a > 0)
.reverse()
.join(" + ");
非同步處理
wait
code:javascript
var wait = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms));
var elms = Array.from(document.querySelectorAll(div));
var $elm;
while (($elm = elms.shift())) {
await wait(17);
$elm.click();
$elm.dispatchEvent(
new MouseEvent("contextmenu", {
view: window,
bubbles: true,
cancelable: true,
})
);
document.querySelector([elm]).click();
}
CORS POST
code:javascript
async function postHandler(e) {
name = '';
key = '';
secret = '';
text = e.target.value;
const oauth = OAuth({
consumer: { key, secre },
signature_method: "HMAC-SHA1",
hash_function(base_string, key) {
return CryptoJS.HmacSHA1(base_string, key).toString(CryptoJS.enc.Base64);
}
});
const options = {
url: '',
method: 'POST',
data: { text, name, key, type: "json" }
};
const cors_support = "https://corsproxy.io/?";
const res = await fetch(cors_support + options.url, {
method: options.method,
body: new URLSearchParams(options.data),
headers: oauth.toHeader(oauth.authorize(options))
}).then(r => r.json());
document.all.output.value = res.resultset.result.text;
}
@Shenqingchuan: 学 JS 快 5 年,今天又被贺老的代码教学了🤣
我真是第一次知道原来 JS 的解构上面也能用动态 key
😢 太牛了
https://pbs.twimg.com/media/F6X1fgyawAA9Dnt.jpg
code:javascript
let arr = 1, 2, 3;
let {0: first, arr.length - 1: last} = arr;
// first = 1
// last = 3
Debounce
Debounce – How to Delay a Function in JavaScript (JS ES6 Example)
code:javascript
function debounce(func, timeout = 300){
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => { func.apply(this, args); }, timeout);
};
}
調整viewport
code:javascript
const adjustViewport = () => {
const triggerWidth = 375;
const viewport = document.querySelector('metaname="viewport"');
const value = window.outerWidth < triggerWidth
? width=${triggerWidth}, target-densitydpi=device-dpi
: 'width=device-width, initial-scale=1';
viewport.setAttribute('content', value);
}
const debouncedResize = debounce(adjustViewport)
window.addEventListener('resize', debouncedResize, false)
Web 终极拦截技巧(全是骚操作) | 风痕 · 術&思
Any problem in computer science can be solved by another layer of indirection.
覆寫 API
網路相關
xhr、fetch、WebSocket
原型
Array.prototype.at = ...
重新導向
window.open、history.go back pushState
移除禁用
1loc
あなたが知らないであろう15個の強力なJavaScriptのテクニック🗡🔈🔥
便利ページ:Javascript でちょっとした便利な機能を作ってみた
JavaScriptの小技集 #JavaScript - Qiita
RobinMalfait/lazy-collections: Collection of fast and lazy operations